package com.xhdx.threadpool.tools;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 阻塞队列：可用于处理生产消费的问题
 * 
 * 实现机制：put/take利用重入锁ReentrantLock实现同步效果
 */
public class ArrayBlockingQueueTest {

    public static void main(String[] args) {
        ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(3);
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        //see put源码
                        abq.put("Hello Java World");
                        System.out.println(Thread.currentThread().getName() + ":放入数据，剩余数据：" + abq.size());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10000);
                        //see take源码
                        abq.take();
                        System.out.println(Thread.currentThread().getName() + ":取出数据，剩余数据：" + abq.size());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
